package com.oa.util;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.HibernateTemplate;
/**
 * Dao操作基类
 * @author Bond
 * @date 2015年10月8日 11:14:46
 */
public class BaseHibernateDAO {
	
	private HibernateTemplate hibernateTemplate;
	
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}
	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}
	/**
	 * 对象加载
	 * @param cls 对象类型
	 * @param Id
	 * @return object
	 */
	protected Object load(Class cls,Serializable Id){
		Object obj = null;
		try {
			obj = this.hibernateTemplate.get(cls, Id);
		} catch (HibernateException he) {
			he.printStackTrace();
		}
		return obj;
	}
	/**
	 * 添加对象
	 * @param obj
	 * @return boolean
	 */
	protected boolean add(Object obj){
		boolean flag = false;
		try {
			this.hibernateTemplate.save(obj);
			flag = true;
		} catch (HibernateException he) {
			he.printStackTrace();
		}
		return flag;
	}
	/**
	 * 删除对象
	 * @param obj
	 * @return boolean
	 */
	protected boolean delete(Object obj){
		boolean flag = false;
		try {
			this.hibernateTemplate.delete(obj);
			flag = true;
		} catch (HibernateException he) {
			he.printStackTrace();
		}
		return flag;
	}
	protected boolean update(Object obj){
		boolean flag = false;
		try {
			this.hibernateTemplate.update(obj);
			flag = true;
		} catch (HibernateException he) {
			he.printStackTrace();
		}
		return false;
	}
	protected List list_map(String hql,Map params){
		Query query = null;
		List list = null;
		try {
			if (params != null&&params.size() > 0) {
				query = this.hibernateTemplate.getSessionFactory().openSession().createQuery(hql);
				Object[] keyArrs = params.keySet().toArray();
				for (int i = 0; i < keyArrs.length; i++) {
					query.setParameter(keyArrs[i].toString(),params.get(keyArrs[i]));
				}
				list = query.list();
			} else {
				list = this.hibernateTemplate.find(hql);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
}
